package org.budo.dubbo.protocol.http.aop.permission.user;

import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.budo.dubbo.protocol.http.authentication.AuthenticationCheckService;
import org.budo.dubbo.protocol.http.authentication.AuthenticationCheckService.Fail;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
public class UserPermissionCheckHandlerInterceptor extends AbstractUserPermissionCheckInterceptor implements HandlerInterceptor {
    /**
     * @see UserPermissionCheckMethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (null == handler || !(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        UserPermissionCheck methodAnnotation = handlerMethod.getMethodAnnotation(UserPermissionCheck.class);
        if (null == methodAnnotation) {
            return true;
        }

        AuthenticationCheckService _authenticationCheckService = this.getAuthenticationCheckService();
        if (null == _authenticationCheckService) {
            log.error("#38 _authenticationCheckService is null, handler=" + handler);
            return true;
        }

        Serializable _authenticationPrincipal = _authenticationCheckService.getAuthenticationPrincipal();
        if ((null == _authenticationPrincipal || _authenticationPrincipal instanceof Fail)) {
            this.handleAuthFailed(handlerMethod.getMethod(), _authenticationPrincipal);
            return false;
        }

        String permissionName = this.permissionName(handlerMethod.getMethod());

        Boolean hasPermission = this.hasPermission(_authenticationPrincipal, permissionName);
        if (hasPermission) {
            return true; // 权限检查通过
        }

        this.handlePermissionFailed(_authenticationPrincipal, permissionName);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //
    }
}